<template>
	<view class="content">
		<view class="gradient-bg">
			<!-- 渐变背景 -->
			<view class="list-card-wrap">
				<view class="flex-row-between" style="margin-bottom: 8rpx;">
					<view class="flex-row">
						<text class="white-text font-24">单据编号</text>
						<text class="white-text font-24" style="margin-left: 20rpx;">{{ taskInfo.no }}</text>
					</view>
				</view>
				<view class="list-card">
					<view class="">
						<text class="black-text-34">{{ taskInfo.supplierName }}</text>
					</view>
					<view class="content-blue flex-row">
						<view class="flex-column flex1">
							<text class="gray-text">到货总数</text>
							<text class="black-text">{{ taskInfo.totalQty }}</text>
						</view>
						<view class="split"></view>
						<view class="flex-column flex1">
							<text class="gray-text">收货总数</text>
							<text class="black-text">{{ taskInfo.checkTotalQty || 0 }}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="s-input-wrap">
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">托盘号</text>
					<input auto-focus="true" v-model="trayNo" class="s-input flex1" placeholder="请输入或扫描托盘号" />
					<image v-if="trayNo" class="s-input-icon clear-icon" src="/static/images/clear.png"
						@click="clearTrayNo"></image>
					<image class="s-input-icon" src="/static/images/scan.png"></image>
				</view>
			</view>
			<view class="s-input-wrap">
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">物料编号</text>
					<input v-model="productNo" @confirm="handleScan" class="s-input flex1" placeholder="请输入或扫描物料编号" />
					<image v-if="productNo" class="s-input-icon clear-icon" src="/static/images/clear.png"
						@click="clearField"></image>
					<image class="s-input-icon" src="/static/images/scan.png"></image>

				</view>
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">物料名称</text>
					<text class="black-text font-30">{{ product.productName }}</text>
				</view>
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">需求数量</text>
					<text class="black-text font-30">{{ getArrivalQtyTxt(product.arrivalQty) }}</text>
				</view>
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">已收数量</text>
					<text class="black-text font-30">{{ getArrivalQtyTxt(product.quantityReceived) }}</text>
				</view>
				<view class="s-input-box flex-row">
					<text class="gray-text font-30">收货数量</text>
					<input @input="setNum" type="number" v-model="product.qty" class="s-input flex1"
						placeholder="请输入收货数量" />
				</view>
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">生产日期</text>
					<picker mode="date" :value="productDate" @change="bindProductDateChange">
						<view class="black-text font-30">{{ productDate ? productDate : '请选择生产日期' }}</view>
					</picker>
				</view>
				<view class="s-input-box flex-row-between">
					<text class="gray-text font-30">有效期至</text>
					<text class="gray-text font-30">{{ productObj.qualityGuaranteePeriodTemp }}</text>
				</view>
			</view>

			<view @click="addDetail" class="botton p-botton font-30"
				style="height: 92rpx; line-height:92rpx;margin: 0 25rpx;">
				收货
			</view>
		</view>

		<view class="table-wrap" style="padding-bottom: 100rpx;">
			<view class="flex-row-start" style="margin: 10rpx 0;">
				<text class="gray-text font-24">收货纪录</text>
				<uni-icons type="top" size="14" style="color: #8997A8;"></uni-icons>
			</view>
			<zb-table @dele="deleteDetail" :show-header="true" :columns="detailColumns" :fit="true" :border="true"
				:data="detailData">
			</zb-table>
		</view>

		<view class="content-list-total flex-row-between">
			<text class="gray-text">合计:</text>
			<view class="flex-row">
				<text class="gray-text">共
					<text class="blue-text font-38">{{ taskInfo.checkTotalQty || 0 }}</text>
					件
				</text>
				<view @click="completeTask" class="botton p-botton">完成</view>
			</view>
		</view>

	</view>
</template>

<script>
import {
	validNum,
	addDaysToDate
} from "@/utils/common"
import {
	getTaskInfoById,
	getBillReceiveDetailList,
	getBillProductList,
	addReceiveDetail,
	delByReceiveDetail,
	complete,
	getTaskInfoByCode
} from "./api"

export default {
	onLoad(option) {
		this.taskId = option.id;
	},
	created() {
		this.getTaskDetail();
	},
	data() {
		return {
			taskId: '',
			taskInfo: {},
			trayNo: '',
			productNo: "",
			productObj: {},
			detailData: [],
			productData: [],
			product: {},
			productDate: '',
			detailColumns: [{
				type: 'index',
				label: '序号',
				align: 'center',
				width: 40
			},
			{
				name: 'trayNo',
				label: '托盘号',
				fixed: false,
				emptyString: '--'
			},
			{
				name: 'productNo',
				label: '物料编号',
				fixed: false,
				emptyString: '--'
			},
			{
				name: 'batchNo',
				label: '批次号',
				fixed: false,
				emptyString: '--'
			},
			{
				name: 'productName',
				label: '物料',
				sorter: false,
			},
			{
				name: 'qty',
				label: '数量'
			},
			{
				name: 'productionDate',
				label: '生产日期'
			},
			{
				name: 'expiryDate',
				label: '有效日期'
			},
			{
				name: 'operation',
				type: 'operation',
				label: '操作',
				renders: [{
					name: '/static/images/delete.png',
					type: 'icon',
					func: "dele",
					style: "width:24rpx;height:28rpx"
				},],
			},
			],

		}
	},
	methods: {
		getTaskDetail() {
			getTaskInfoById(this.taskId).then(res => {
				if (res.code == 200) {
					this.taskInfo = res.data
					// 继续查询收货任务明细
					getBillReceiveDetailList({
						billNo: this.taskInfo.no,
						pageNum:1,
						pageSize: 999
					}).then(res => {
						if (res.code == 200) {
							this.productData = res.rows;
						}
					})
					this.getBillProductList()
				}
			})
		},
		// 查询收货清单(物料列表)
		getBillProductList() {
			getBillProductList({
				billNo: this.taskInfo.no,
				pageNum:1,
				pageSize: 999
			}).then(res => {
				if (res.code == 200) {
					this.detailData = res.rows;
				}
			})
		},
		clearField() {
			this.productNo = ''
			this.clearObjInfo()
		},
		clearMaterialInfo() {
			this.productObj = ''
			this.product = ''
			this.productDate = ''
		},
		handleScan() {
			getTaskInfoByCode(this.productNo).then(res => {
				if (res.code == 200) {
					this.clearMaterialInfo()
					this.productObj = res.data || {}
					if (res.data) {
						this.bindPickerProductTwo(res.data.productNo)
					} else {
						this.$modal.msg("此物料不在订单中");
					}
				}
			})
		},
		// 数量校验
		setNum(e) {
			this.$set(this.product, 'qty', validNum(e))
		},
		bindPickerProductTwo(no) {
			if (!this.productData || this.productData.length == 0) {
				return;
			}

			let o = this.productData.find(el => el.productNo == no)
			if (!o) {
				this.clearObjInfo()
				this.$modal.msg("此物料不在订单中");
				return
			}
			this.product = o
			this.product.arrivalQty = this.product.qty
			this.product.quantityReceived = this.getQuantityReceived();
			// this.product.qty = this.product.qty - this.getQuantityReceived();
			if(this.productObj?.cgPsConver){
				this.product.qty =Math.floor(Number(this.product.qty - this.getQuantityReceived())/Number(this.productObj?.cgPsConver)) ;
			}else{
				this.product.qty = this.product.qty - this.getQuantityReceived()
			}
		},
		bindProductDateChange(e) {
			this.productDate = e.detail.value
			if (this.productObj.qualityGuaranteePeriod) {
				this.product.batchNo = addDaysToDate(this.productDate, 0, 1)
				this.productObj.qualityGuaranteePeriodTemp = addDaysToDate(this.productDate, this.productObj.qualityGuaranteePeriod)
			}
		},
		getArrivalQtyTxt(num) {
			try {
				if (!num || typeof num !== 'number') {
					return num;
				}

				const cgPsConver = Number(this.productObj?.cgPsConver);
				if (!cgPsConver) {
					return num;
				}

				const wholeUnits = Math.floor(num / cgPsConver);
				const remainder = num % cgPsConver;
				
				if (!this.productObj?.cgUnitName || (remainder > 0 && !this.productObj?.specUnitName)) {
					return num;
				}

				const mainUnit = wholeUnits + this.productObj.cgUnitName;
				return remainder > 0 
					? `${mainUnit}${remainder}${this.productObj.specUnitName}`
					: mainUnit;
					
			} catch (error) {
				console.warn('Error', error);
				return num;
			}
		},
		// 校验收货数量不能大于需求数量
		validQty() {
			let productNum = parseFloat(this.product.qty)
			this.detailData.forEach(item => {
				if (item.productNo == this.product.productNo) {
					productNum += parseFloat(item.qty)
				}
			})
			if (productNum > this.product.arrivalQty) {
				return false
			}
			return true
		},
		//获取已收数量
		getQuantityReceived() {
			let productNum = parseFloat(0)
			this.detailData.forEach(item => {
				if (item.productNo == this.product.productNo) {
					productNum += parseFloat(item.qty)
				}
			})
			return productNum
		},
		// 加入收货单
		addDetail() {
			if (!this.trayNo) {
				this.$modal.msg("请输入托盘号");
				return;
			}
			if (!this.product.productNo) {
				this.$modal.msg("请先选择物料");
				return;
			}
			if (!this.validQty()) {
				this.$modal.msg("物料收货数量大于需求数量");
				return;
			}
			if (!this.productDate) {
				this.$modal.msg("请选择生产日期");
				return;
			}
			let obj = {
				billNo: this.taskInfo.no,
				trayNo: this.trayNo,
				productNo: this.product.productNo,
				productName: this.product.productName,
				productUnit: this.product.productUnit,
				qty:this.productObj?.cgPsConver ?( Number(this.product.qty)*Number(this.productObj?.cgPsConver)) : this.product.qty,
				batchNo: this.product.batchNo,
				productDate: this.productDate,
				validDate: this.productObj.qualityGuaranteePeriodTemp
			}
			this.$modal.loading("加载中...")
			addReceiveDetail(obj).then(res => {
				this.$modal.closeLoading()
				if (res.code == 200) {
					this.$modal.msgSuccess("操作成功");
					let barcodeObj = {
						productNo: this.product.productNo,
						quantity: this.product.qty
					}
					this.getTaskDetail();
				} else {
					res.msg && this.$modal.confirmClose(res.msg)
				}
				this.clearObjInfo()
			})
		},
		clearObjInfo() {
			this.productDate = '';
			this.productNo = '';
			this.product = {};
			this.productObj = {}
		},
		deleteDetail(row) {
			this.$modal.confirm('是否确认删除数据').then(() => {
				this.$modal.loading("加载中...")
				delByReceiveDetail(row).then(res => {
					this.$modal.closeLoading()
					if (res.code == 200) {
						this.$modal.msgSuccess("操作成功");
						this.getTaskDetail();
					} else {
						res.msg && this.$modal.confirmClose(res.msg)
					}
				})
			})
		},
		completeTask() {
			let confimText = '是否确认完成？'
			if (this.taskInfo.checkTotalQty < this.taskInfo.totalQty) {
				confimText = '收货总数小于到货总数,是否确认完成？'
			}
			this.$modal.confirm(confimText).then(() => {
				this.$modal.loading("加载中...")
				complete({
					no: this.taskInfo.no
				}).then(res => {
					this.$modal.closeLoading()
					if (res.code == 200) {
						this.$modal.msgSuccess("操作成功");
						// 延迟1秒跳转
						uni.$emit('refreshList', {
							msg: '页面更新'
						})
						setTimeout(() => {
							uni.navigateBack();
						}, 1000);
					} else {
						res.msg && this.$modal.confirmClose(res.msg)
					}
				})
			})
		},
		clearTrayNo() {
			this.trayNo = '';
		},
	}
}
</script>

<style>
page {
	background-color: #F8F8F8;
}
</style>
<style scoped></style>